package com.bjh.controller;

import com.bjh.service.AgentService;
import com.bjh.util.BaseController;
import com.bjh.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/agent/login")
public class LoginController extends BaseController {
    @Autowired
    private AgentService agentService;

    /**
     * 代理商登录
     * @param account 账号或者手机号
     * @param password 密码
     * @return {@link Map}
     */
    @GetMapping("accountLogin")
    public Map<String, Object> accountLogin (@RequestParam String account, @RequestParam String password) {
        logBefore(log, "++++++++++ 代理商登录 ++++++++++");
        Map<String, Object> resMap = new HashMap<>();
        try{
            Map<String, Object> agentMap = agentService.getAgentByAccountOrMobile(account);
            if(Objects.isNull(agentMap)){
                logAfter(log);
                return returnResult(1,"该代理商不存在");
            } else{
                if(Objects.equals(MD5.md5(password), agentMap.get("password"))){
                    resMap.put("id", agentMap.get("id"));
                    resMap.put("name", agentMap.get("name"));
                    logAfter(log);
                    return returnSuccessWithData(resMap);
                }else {
                    logAfter(log);
                    return returnResult(1,"密码错误");
                }
            }
        } catch(Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return returnResult(1,"登录失败");
        }
    }
}
